﻿from google.appengine.api import users

from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect,HttpResponse
from django.core.paginator import Paginator

from blog.models import *
from blog.utils import *
from blog.utils import _cntime

def index(request):
    """WAP 首页"""
    archives = Archive.all().order('-pub_date')[:10]
    return render_to_response('wap/index.html',dict(archives=archives))

def archives(request):
    """查看所有文章"""
    objects = Archive.all().order('-pub_date')
    p = Paginator(objects,5)
    archives = p.page(request.GET.get('page',1))
    return render_to_response('wap/archives.html',dict(archives=archives))

def categories(request):
    """查看所有分类"""
    categories = Category.all()
    return render_to_response('wap/categories.html',dict(categories=categories))

def comments(request):
    """最新评论"""
    objects = Comment.all().order('-date')
    p = Paginator(objects,10)
    comments = p.page(request.GET.get('page',1))
    return render_to_response('wap/comments.html',dict(comments=comments))

def archive(request,id):
    """查看文章"""
    archive = Archive.get_by_id(int(id))
    archive.view_nums += 1
    archive.put()
    if not archive:
        return HttpResponseRedirect('/wap/not_found')

    return render_to_response('wap/archive.html',dict(archive=archive))


def category(request,name):
    """查看分类"""
    category = Category.get_by_key_name(name)
    if not category:
        return HttpResponseRedirect('/wap/not_found')
    return render_to_response('wap/category.html',dict(category=category))

@clear_cache()
def add_comment(request,archive_id):
    if not request.method == 'POST':
        return HttpResponseRedirect('/wap')
    name = request.POST.get('name')
    archive = Archive.get_by_id( int(archive_id )) 
    if not archive:
        # 文章不存在
        return HttpResponseRedirect('/wap/not_found')

    comment = Comment( archive = archive,
        name = name,
        email = name + '@mobile.me',
        content = request.POST.get('content'),
        date = _cntime(),
        # 转换为北京区时间
        source = 'wap',
    )
    comment.put()

    return HttpResponseRedirect( '/wap%s#comment_%d' % (
        archive.get_absolute_url(),comment.key().id() )
    )


